<template>
  <div class="bicycles-container">
    <!-- 操作提示 -->
    <div class="operation-tip" v-if="isSelectingLocation">
      <el-alert title="请在地图上点击选择单车位置" type="warning" :closable="false" show-icon />
    </div>

    <div class="main-content">
      <!-- 地图容器 -->
      <div id="bikeMapDiv" class="map-view"></div>

      <!-- 右侧功能面板 -->
      <div class="control-panel">
        <el-card class="control-card">
          <template #header>
            <div class="card-header">
              <span>单车管理</span>
              <div class="bike-icon"></div>
            </div>
          </template>

          <!-- 筛选区域 -->
          <div class="filter-section">
            <el-select
              v-model="filterStatus"
              placeholder="按状态筛选"
              clearable
              @change="filterBikes"
            >
              <el-option label="可用" value="可用"></el-option>
              <el-option label="使用中" value="使用中"></el-option>
              <el-option label="维修中" value="维修中"></el-option>
              <el-option label="损坏" value="损坏"></el-option>
            </el-select>
            <el-select
              v-model="filterType"
              placeholder="按类型筛选"
              clearable
              @change="filterBikes"
            >
              <el-option label="普通单车" value="普通单车"></el-option>
              <el-option label="电动单车" value="电动单车"></el-option>
              <el-option label="折叠单车" value="折叠单车"></el-option>
            </el-select>
          </div>

          <div class="control-buttons">
            <el-button type="primary" @click="startAddBike" class="bike-button">
              <el-icon><Plus /></el-icon> 添加单车
            </el-button>
          </div>

          <div class="operation-tip" v-if="!isAddingBike">
            <el-alert
              title="提示：点击添加单车按钮，然后在地图上选择单车位置"
              type="info"
              :closable="false"
              show-icon
              class="tip-alert"
            />
          </div>

          <div class="selected-info" v-if="newLocation && !showBikeDialog">
            <div class="location-title">已选择位置</div>
            <el-descriptions :column="1" border size="small" class="bike-descriptions">
              <el-descriptions-item label="经度">
                <span class="coordinate-value">{{ newLocation?.x.toFixed(6) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="纬度">
                <span class="coordinate-value">{{ newLocation?.y.toFixed(6) }}</span>
              </el-descriptions-item>
            </el-descriptions>
            <div class="mt-2">
              <el-button type="primary" @click="showBikeDialog = true" class="continue-button">
                <el-icon class="el-icon--left"><ArrowRight /></el-icon>继续填写单车信息
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 添加单车表单对话框 -->
    <el-dialog
      v-model="showBikeDialog"
      :title="isEditing ? '编辑单车信息' : '添加单车信息'"
      width="50%"
      destroy-on-close
      custom-class="bike-dialog"
    >
      <el-form
        :model="bikeForm"
        label-width="120px"
        ref="bikeFormRef"
        :rules="formRules"
        class="bike-form"
      >
        <el-form-item label="单车ID" prop="BikeId">
          <el-input
            v-model="bikeForm.BikeId"
            placeholder="请输入单车ID"
            :disabled="isEditing"
          ></el-input>
        </el-form-item>
        <el-form-item label="单车类型" prop="BikeType">
          <el-select v-model="bikeForm.BikeType" placeholder="请选择单车类型" style="width: 100%">
            <el-option label="普通单车" value="普通单车"></el-option>
            <el-option label="电动单车" value="电动单车"></el-option>
            <el-option label="折叠单车" value="折叠单车"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前地址" prop="NowAddress">
          <el-input v-model="bikeForm.NowAddress" placeholder="请输入当前地址"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="Status">
          <el-select v-model="bikeForm.Status" placeholder="请选择状态" style="width: 100%">
            <el-option label="可用" value="可用"></el-option>
            <el-option label="使用中" value="使用中"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="损坏" value="损坏"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电量" prop="BatteryLevel" v-if="bikeForm.BikeType === '电动单车'">
          <el-input v-model="bikeForm.BatteryLevel" placeholder="请输入电量百分比"></el-input>
        </el-form-item>
        <el-form-item label="当前使用者ID" v-if="bikeForm.Status === '使用中'">
          <el-input v-model="bikeForm.CurrentUseUserId" placeholder="请输入使用者ID"></el-input>
        </el-form-item>
        <el-form-item label="借用时间" v-if="bikeForm.Status === '使用中'">
          <el-input v-model="bikeForm.BorrowTime" placeholder="请输入借用时间"></el-input>
        </el-form-item>
        <el-form-item label="维护状态" v-if="bikeForm.Status === '维修中'">
          <el-select v-model="bikeForm.MaintenanceStatus" placeholder="请选择维护状态" style="width: 100%">
            <el-option label="等待维修" value="等待维修"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="维修完成" value="维修完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="维护原因"
          v-if="bikeForm.Status === '维修中' || bikeForm.Status === '损坏'"
        >
          <el-input
            v-model="bikeForm.MaintenanceReason"
            type="textarea"
            :rows="3"
            placeholder="请输入维护原因"
          ></el-input>
        </el-form-item>
        <el-form-item label="位置">
          <div class="location-info">
            <el-tag v-if="newLocation" type="success">已选择位置</el-tag>
            <el-tag v-else type="warning">请在地图上点击选择位置</el-tag>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelBikeOperation">取消</el-button>
          <el-button type="primary" @click="saveBike" :disabled="!newLocation && !isEditing">
            {{ isEditing ? '保存修改' : '添加单车' }}
          </el-button>
          <el-button type="danger" @click="confirmDeleteBike" v-if="isEditing">删除单车</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 操作成功提示对话框 -->
    <el-dialog
      v-model="showSuccessDialog"
      :title="successTitle"
      width="30%"
      custom-class="success-dialog"
    >
      <div class="success-content">
        <el-icon class="success-icon"><CircleCheckFilled /></el-icon>
        <p>{{ successMessage }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeSuccessDialog">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="showDeleteConfirmDialog"
      title="确认删除"
      width="30%"
      custom-class="confirm-dialog"
    >
      <div class="confirm-content">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <p>确定要删除此单车吗？此操作不可恢复。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteConfirmDialog = false">取消</el-button>
          <el-button type="danger" @click="deleteBike">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { Plus, CircleCheckFilled, ArrowRight, WarningFilled } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import Point from '@arcgis/core/geometry/Point'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import gaodeLayer from '@/utils/GaoDeBaseLayer'

// 状态变量
const showBikeDialog = ref(false)
const showSuccessDialog = ref(false)
const showDeleteConfirmDialog = ref(false)
const isAddingBike = ref(false)
const isSelectingLocation = ref(false)
const isEditing = ref(false)
const successTitle = ref('操作成功')
const successMessage = ref('')
const filterStatus = ref('')
const filterType = ref('')
let newLocation: Point | null = null
let tempGraphic: Graphic | null = null
let selectedBikeOID: number | null = null
const bikeFormRef = ref<FormInstance | null>(null)

// 表单数据
const bikeForm = ref({
  BikeId: '',
  BikeType: '',
  NowAddress: '',
  Status: '',
  BatteryLevel: '',
  IsAvailable: '是',
  CurrentUseUserId: '',
  BorrowTime: '',
  MaintenanceStatus: '',
  MaintenanceReason: '',
  TotalUsageCount: '0',
})

// 表单验证规则
const formRules = {
  BikeId: [{ required: true, message: '请输入单车ID', trigger: 'blur' }],
  BikeType: [{ required: true, message: '请选择单车类型', trigger: 'change' }],
  NowAddress: [{ required: true, message: '请输入当前地址', trigger: 'blur' }],
  Status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 地图和图层引用
let view: MapView | null = null
let bikeLayer: FeatureLayer | null = null

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})

// 监听状态变化，动态显示/隐藏表单项
watch(
  () => bikeForm.value.Status,
  (newVal) => {
    // 当状态改变时，重置相关字段
    if (newVal !== '使用中') {
      bikeForm.value.CurrentUseUserId = ''
      bikeForm.value.BorrowTime = ''
    }
    if (newVal !== '维修中') {
      bikeForm.value.MaintenanceStatus = ''
      if (newVal !== '损坏') {
        bikeForm.value.MaintenanceReason = ''
      }
    }
  },
)

// 初始化地图
const initMap = () => {
  try {
    // 创建地图实例
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
    })

    // 创建地图视图
    view = new MapView({
      container: 'bikeMapDiv',
      map: map,
      center: [116.3, 39.9], // 北京的经纬度
      zoom: 10,
    })

    // 创建单车点要素图层
    bikeLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/rDRhdC4brwj3FLD5/arcgis/rest/services/cycleFeaturelayer/FeatureServer/0',
      outFields: ['*'], // 获取所有字段
      renderer: {
        type: 'simple',
        symbol: new SimpleMarkerSymbol({
          color: [0, 112, 255],
          outline: {
            color: [255, 255, 255],
            width: 2,
          },
          size: 12,
        }),
      },
    })

    // 添加图层到地图
    map.add(bikeLayer)

    // 添加点击事件
    view.on('click', (event) => {
      if (isAddingBike.value && isSelectingLocation.value) {
        // 如果正在添加单车并且在选择位置状态，记录点击位置
        newLocation = view!.toMap(event)

        // 添加临时标记
        addTempMarker(
          new Point({
            x: newLocation.x,
            y: newLocation.y,
            spatialReference: view!.spatialReference,
          }),
        )

        // 选择位置后，关闭选择位置状态
        isSelectingLocation.value = false
        showBikeDialog.value = true
        return
      }
    })

    // 添加点击要素事件
    if (view?.popup) {
      view.popup.autoCloseEnabled = false // 禁用自动弹出
    }
    view.on('click', (event) => {
      console.log(isAddingBike.value)
      // 如果正在添加单车，不执行选择操作
      if (isAddingBike.value) return

      // 构建查询参数
      const query = bikeLayer!.createQuery()
      query.outFields = ['*']
      query.distance = 1000
      query.units = 'meters'
      query.returnGeometry = true
      query.geometry = view!.toMap(event)
      query.spatialRelationship = 'intersects'
      console.log(query)
      // 执行查询
      bikeLayer!.queryFeatures(query).then((results) => {
        console.log(results.features)
        const feature = results.features[0]
        if (feature) {
          // 获取要素的属性
          const attributes = feature.attributes
          selectedBikeOID = attributes.OBJECTID

          // 设置编辑模式
          isEditing.value = true

          // 填充表单数据
          bikeForm.value = {
            BikeId: attributes.BikeId || '',
            BikeType: attributes.BikeType || '',
            NowAddress: attributes.NowAddress || '',
            Status: attributes.Status || '',
            BatteryLevel: attributes.BatteryLevel || '',
            IsAvailable: attributes.IsAvailable || '是',
            CurrentUseUserId: attributes.CurrentUseUserId || '',
            BorrowTime: attributes.BorrowTime || '',
            MaintenanceStatus: attributes.MaintenanceStatus || '',
            MaintenanceReason: attributes.MaintenanceReason || '',
            TotalUsageCount: attributes.TotalUsageCount || '0',
          }

          // 设置位置
          if (feature.geometry) {
            newLocation = feature.geometry as Point
          }

          // 显示编辑对话框
          showBikeDialog.value = true
        }
      })
    })
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

// 添加临时标记
const addTempMarker = (location: Point) => {
  // 移除之前的临时标记
  if (tempGraphic && view) {
    view.graphics.remove(tempGraphic)
  }

  // 创建新的临时标记
  tempGraphic = new Graphic({
    geometry: location,
    symbol: new SimpleMarkerSymbol({
      color: [0, 112, 255],
      outline: {
        color: [255, 255, 255],
        width: 2,
      },
      size: 12,
    }),
  })

  // 添加到视图
  if (view) {
    view.graphics.add(tempGraphic)
  }
}

// 开始添加单车
const startAddBike = () => {
  isAddingBike.value = true
  isSelectingLocation.value = true // 设置为选择位置状态
  isEditing.value = false
  newLocation = null
  selectedBikeOID = null

  // 显示选择位置提示
  ElMessage.info('请在地图上点击选择单车位置')

  // 重置表单
  bikeForm.value = {
    BikeId: '',
    BikeType: '',
    NowAddress: '',
    Status: '',
    BatteryLevel: '',
    IsAvailable: '是',
    CurrentUseUserId: '',
    BorrowTime: '',
    MaintenanceStatus: '',
    MaintenanceReason: '',
    TotalUsageCount: '0',
  }
}

// 取消操作
const cancelBikeOperation = () => {
  showBikeDialog.value = false
  isAddingBike.value = false
  isSelectingLocation.value = false // 重置选择位置状态
  isEditing.value = false

  // 清除临时标记
  if (tempGraphic && view) {
    view.graphics.remove(tempGraphic)
  }
  newLocation = null
  selectedBikeOID = null
}

// 保存单车信息
const saveBike = async () => {
  if (!bikeFormRef.value) return

  try {
    // 表单验证
    await bikeFormRef.value.validate()

    // 准备属性数据
    const attributes: any = {
      BikeId: String(bikeForm.value.BikeId),
      BikeType: String(bikeForm.value.BikeType),
      NowAddress: String(bikeForm.value.NowAddress),
      Status: String(bikeForm.value.Status),
      BatteryLevel: String(bikeForm.value.BatteryLevel || ''),
      IsAvailable: String(bikeForm.value.IsAvailable),
      CurrentUseUserId: String(bikeForm.value.CurrentUseUserId || ''),
      BorrowTime: String(bikeForm.value.BorrowTime || ''),
      MaintenanceStatus: String(bikeForm.value.MaintenanceStatus || ''),
      MaintenanceReason: String(bikeForm.value.MaintenanceReason || ''),
      TotalUsageCount: String(bikeForm.value.TotalUsageCount || '0'),
    }

    if (!bikeLayer) {
      ElMessage.error('单车图层未初始化')
      return
    }

    try {
      let results

      if (isEditing.value) {
        // 更新现有单车
        if (selectedBikeOID === null) {
          ElMessage.error('未找到要编辑的单车')
          return
        }

        // 创建更新要素
        const updateFeature = new Graphic({
          attributes: {
            OBJECTID: selectedBikeOID,
            ...attributes,
          },
        })

        // 如果位置改变了，更新几何信息
        if (newLocation) {
          updateFeature.geometry = newLocation
        }

        // 更新要素
        results = await bikeLayer.applyEdits({
          updateFeatures: [updateFeature],
        })

        if (results.updateFeatureResults && results.updateFeatureResults.length > 0) {
          successTitle.value = '更新成功'
          successMessage.value = '单车信息已成功更新！'
          showSuccessDialog.value = true
        } else {
          ElMessage.error('更新单车失败')
        }
      } else {
        // 添加新单车
        if (!newLocation) {
          ElMessage.error('请先在地图上选择位置')
          return
        }

        // 创建新要素
        const newFeature = new Graphic({
          geometry: newLocation,
          attributes: attributes,
        })

        // 添加到图层
        results = await bikeLayer.applyEdits({
          addFeatures: [newFeature],
        })

        if (results.addFeatureResults && results.addFeatureResults.length > 0) {
          successTitle.value = '添加成功'
          successMessage.value = '单车已成功添加到系统！'
          showSuccessDialog.value = true

          // 清除临时标记
          if (tempGraphic && view) {
            view.graphics.remove(tempGraphic)
          }
        } else {
          ElMessage.error('添加单车失败')
        }
      }

      // 关闭对话框
      showBikeDialog.value = false
      // 刷新图层
      if (bikeLayer) {
        bikeLayer.refresh()
      }
    } catch (error) {
      console.error('保存单车信息时出错:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('表单验证失败，请检查输入')
  }
}

// 确认删除单车
const confirmDeleteBike = () => {
  showDeleteConfirmDialog.value = true
}

// 删除单车
const deleteBike = async () => {
  if (!bikeLayer || selectedBikeOID === null) {
    ElMessage.error('未找到要删除的单车')
    return
  }

  try {
    // 删除要素
    const results = await bikeLayer.applyEdits({
      deleteFeatures: [{ objectId: selectedBikeOID }],
    })

    if (results.deleteFeatureResults && results.deleteFeatureResults.length > 0) {
      successTitle.value = '删除成功'
      successMessage.value = '单车已成功从系统中删除！'
      showSuccessDialog.value = true

      // 关闭对话框
      showDeleteConfirmDialog.value = false
      showBikeDialog.value = false

      // 清除临时标记
      if (tempGraphic && view) {
        view.graphics.remove(tempGraphic)
      }

      // 重置状态
      newLocation = null
      selectedBikeOID = null
      isEditing.value = false

      // 刷新图层
      bikeLayer.refresh()
    } else {
      ElMessage.error('删除单车失败')
    }
  } catch (error) {
    console.error('删除单车时出错:', error)
    ElMessage.error('删除失败，请稍后重试')
  }
}

// 筛选单车
const filterBikes = () => {
  if (!bikeLayer) return

  let whereClause = '1=1' // 默认显示所有

  // 根据状态筛选
  if (filterStatus.value) {
    whereClause += ` AND Status = '${filterStatus.value}'`
  }

  // 根据类型筛选
  if (filterType.value) {
    whereClause += ` AND BikeType = '${filterType.value}'`
  }

  // 应用筛选
  bikeLayer.definitionExpression = whereClause
}

// 关闭成功对话框并重置状态
const closeSuccessDialog = () => {
  showSuccessDialog.value = false
  isAddingBike.value = false
  isEditing.value = false
  newLocation = null
  selectedBikeOID = null
}
</script>

<style scoped>
.bicycles-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.main-content {
  display: flex;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  gap: 16px;
}

.map-view {
  flex: 1;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  min-height: 500px;
}

.control-panel {
  width: 350px;
  z-index: 10;
  display: flex;
  flex-direction: column;
}

.control-card {
  background-color: rgba(255, 255, 255, 0.98);
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  border: none;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  color: #2c3e50;
  font-weight: bold;
  font-size: 18px;
  padding-bottom: 8px;
  border-bottom: 2px solid #eaeaea;
}

.bike-icon {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 30px;
  height: 30px;
  background-color: rgba(0, 112, 255, 0.2);
  border-radius: 50%;
  z-index: -1;
}

.filter-section {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
  margin-top: 16px;
}

.control-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 16px;
}

.bike-button {
  width: 100%;
  margin-top: 16px;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
}

.location-selection-tip {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 20;
  width: 300px;
}

.location-title {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eaeaea;
}

.coordinate-value {
  font-family: 'Courier New', monospace;
  color: #0070ff;
  font-weight: 500;
}

.tip-alert {
  margin-top: 16px;
  border-radius: 8px;
}

.mt-2 {
  margin-top: 16px;
  text-align: center;
}

.continue-button {
  width: 80%;
  border-radius: 8px;
  font-weight: 500;
}

.bike-descriptions {
  margin-top: 8px;
}

.success-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
  background-color: #f0f9eb;
  border-radius: 8px;
}

.success-icon {
  font-size: 48px;
  color: #67c23a;
  margin-bottom: 16px;
}

.warning-icon {
  font-size: 48px;
  color: #e6a23c;
  margin-bottom: 16px;
}

.confirm-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
  background-color: #fdf6ec;
  border-radius: 8px;
}

.bike-dialog .el-dialog__header,
.success-dialog .el-dialog__header,
.confirm-dialog .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #eaeaea;
}

.bike-dialog .el-dialog__body {
  padding: 24px 20px;
}

.bike-form .el-form-item__label {
  font-weight: 500;
}

.success-dialog .el-dialog__header {
  background-color: #f0f9eb;
  padding: 16px 20px;
  border-bottom: 1px solid #e1f3d8;
}

.confirm-dialog .el-dialog__header {
  background-color: #fdf6ec;
  padding: 16px 20px;
  border-bottom: 1px solid #faecd8;
}

.success-dialog .el-dialog__body,
.confirm-dialog .el-dialog__body {
  padding: 24px;
}
</style>
